package com.hrm.interceptor;

import com.hrm.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");

        try {
            //从redis中获取相同的token，验证token是否有效
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);
            if (redisToken == null) {
                throw new Exception("token无效，无权访问");
            }
            //验证token

            Claims claims = jwtUtil.parseJWT(token);

            //获取员工的角色信息
            Object roles = claims.get("roles");
            //获取员工的id信息
            String id = claims.getId();
            //获取员工的loginname信息
            String loginname = claims.getSubject();
            //打印日志
            System.out.println("token有效，用户信息：" + loginname + "，角色：" + roles + "，id：" + id);

            //存储用户信息到request中
            request.getSession().setAttribute("roles", roles);
            request.getSession().setAttribute("id", id);
        } catch (Exception e) {
            //判断是否有权限访问该接口
            throw new Exception("token无效，无权访问");

        }
        return true;
    }
}
